package graph.day15;

import java.util.*;

public class Leetcode_103 {

    List<List<Integer>> res = new ArrayList<>();

    List<Integer> tmp = new ArrayList<>();

    Queue<TreeNode> queue = new LinkedList<>();

    int level = 0;

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if (root == null) return res;
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            if (level % 2 == 0) {
                res.add(new ArrayList<>(tmp));
            } else {
                List<Integer> copied = new ArrayList<>(tmp);
                Collections.reverse(copied);
                res.add(copied);
            }
            level++;
            tmp.clear();
        }
        return res;
    }
}
